package com.dyj.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dyj.common.client.AuthClient;
import com.dyj.common.config.AgentConfiguration;
import com.dyj.common.domain.DyAppletResult;
import com.dyj.common.domain.UserTokenInfo;
import com.dyj.common.domain.query.AppsV2TokenQuery;
import com.dyj.common.domain.query.UserInfoQuery;
import com.dyj.common.domain.vo.AppsV2TokenVo;
import com.dyj.common.service.IAgentTokenService;
import com.dyj.common.utils.DyConfigUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * appsV2Token拦截器
 **/
@Component
public class BodyAppsV2TokenInterceptor implements Interceptor<Object> {

    private final Log log = LogFactory.getLog(BodyAppsV2TokenInterceptor.class);

    @Resource
    private AuthClient authClient;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        Integer tenantId = null;
        String clientKey = "";
        Object[] arguments = request.getArguments();
        for (Object argument : arguments) {
            if(argument instanceof UserInfoQuery){
                UserInfoQuery query = (UserInfoQuery) argument;
                tenantId = query.getTenantId();
                clientKey = query.getClientKey();
            }
        }
        //AppsV2TokenVo appsV2Token = DyConfigUtils.getAgentTokenService().getAppsV2Token(tenantId, clientKey);
        Integer finalTenantId = tenantId;
        String finalClientKey = clientKey;
        AppsV2TokenVo appsV2Token = DyConfigUtils.getAgentTokenService().computeAppsV2TokenIfAbsent(tenantId, clientKey,()->{
            AgentConfiguration agent = DyConfigUtils.getAgent(finalTenantId, finalClientKey);
            AppsV2TokenQuery query = new AppsV2TokenQuery();
            query.setAppid(agent.getClientKey());
            query.setSecret(agent.getClientSecret());
            DyAppletResult<AppsV2TokenVo> result = authClient.appsV2Token(query);
            if (Objects.nonNull(result) && Objects.nonNull(result.getData()) && StringUtils.hasLength(result.getData().getAccess_token())) {
                return result.getData();
            }
            return null;
        });
        if (Objects.isNull(appsV2Token)) {
            throw new RuntimeException("access_token is null");
        }
        request.addBody("access_token", appsV2Token.getAccess_token());
        return true;
    }

    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        StringBuilder sb = new StringBuilder("AccessTokenInterceptor onError ");
        sb.append("url:");
        sb.append(request.getUrl());
        sb.append(", ");
        sb.append("params:");
        sb.append(JSONObject.toJSONString(request.getArguments()));
        sb.append(", ");
        sb.append("result:");
        sb.append(response.getContent());
        sb.append(", ");
        sb.append("msg:");
        sb.append(ex.getMessage());
        log.info(sb.toString());
    }
}
